import { wxRequest } from '../../../utils/server.js';
const _wxRequest = new wxRequest();

const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    address: '',
    regionItem: {},
    cententDetail: {} 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.cententDetail = wx.getStorageSync('chainItem')
    this.setData({
      cententDetail: this.data.cententDetail
    })
  },

  onUnload: function () {
    wx.removeStorageSync('chainItem')
  },

  onHide: function () {
    wx.removeStorageSync('chainItem')
  },

  addressDetail: function (e) {
    this.setData({
      address: e.detail
    })
  },

  formSubmit: function (e) {
    var formdata = e.detail.value;
    var address = this.data.address
    if (address && address.length > 0) {
      formdata.prov = address[0].name
      formdata.proId = address[0].code
      formdata.city = address[1].name
      formdata.cityId = address[1].code
      formdata.disName = address[2].name
      formdata.disId = address[2].code
    }



    if (formdata.chqName == '') {
      wx.showToast({
        icon: 'none',
        title: '连锁总店名称不能为空',
      })
      return 
    }

    if (formdata.detailAddress == '') {
      wx.showToast({
        icon: 'none',
        title: '详细地址不能为空',
      })
      return 
    }

    if (formdata.disId == '' || formdata.disName == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择所在地区',
      })
      return 
    }

    if (formdata.director == '') {
      wx.showToast({
        icon: 'none',
        title: '负责人名称不能为空',
      })
      return 
    }

    if (formdata.mobile == '') {
      wx.showToast({
        icon: 'none',
        title: '手机号码不能为空',
      })
      return
    }

    if (formdata.mobile.length != 11 && formdata.mobile.length != 8 && formdata.mobile.length != 10) {
      wx.showToast({
        icon: 'none',
        title: '手机号码格式不正确',
      })
      return
    }

    if (formdata.mobile.length == '10' && formdata.mobile.slice(0, 2) != '09') {
      // 台湾手机号 09开头+任意8位数
      wx.showToast({
        icon: 'none',
        title: '台湾手机号码格式不正确',
      })
      return
    }

    formdata.regId = this.data.regionItem.id;
    var url = '/org/protected/bizOrg/createChain';
    var title = "发布成功"
    //修改
    if (this.data.cententDetail && this.data.cententDetail.id) {
      url = "/org/protected/bizOrg/updateChain";
      formdata.id = this.data.cententDetail.id;
      title = "修改成功"
    }  


    //请求
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url ,
      method: 'POST',
      data: formdata
    }, (res) => {
      console.log(res)
      if (res.flag) {
        wx.showToast({
          title,
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/publish/chain_store/list',
          })
        }, 1500)
      }
    })
  },


  goback: function () {
    wx.navigateBack({})
  }


})